package service;

import dao.CartDao;
import entity.Address;
import entity.Cart;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

public class CartService {
    private CartDao cartDao = new CartDao();

    public List<Cart> getCartItems(int userId) throws SQLException {
        return cartDao.fetchCartItems(userId);
    }

    public double calculateTotalPrice(List<Cart> items) {
        return items.stream().mapToDouble(item ->item.getQuantity() * item.getPrice()).sum();
    }


    public void updateQuantity(String itemId, int delta) {
        cartDao.updateItemQuantity(itemId, delta);
    }

    public void deleteItem(String itemId) {
        cartDao.removeItem(itemId);
    }

    public void moveToFavorites(String itemId) {
        cartDao.moveToFavorites(itemId);
    }

    public void batchDeleteItems(List<String> list) throws SQLException {
        List<Integer> intList = new ArrayList<>();
        for (String str : list) {
            try {
                int num = Integer.parseInt(str);
                intList.add(num);
            } catch (NumberFormatException e) {
                System.out.println("字符串 " + str + " 无法转换为整数，已跳过");
            }
        }
        cartDao.batchDeleteItems(intList);
    }
    public void addItem(int userId, int productId, int quantity) {
        Timestamp added_at =new Timestamp(System.currentTimeMillis());
        cartDao.addItem(userId,productId,quantity,added_at);
    }

    public Address getDefaultAddress(int userId) {
        return cartDao.getDefaultAddress(userId);
    }
    public void deleteAllItems(int userId) throws SQLException {
        cartDao.deleteAllItems(userId);
    }
}

